package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(urlPatterns = "/*")//过滤器
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        //防止远程访问
//        String ip = request.getRemoteAddr();//获取IP地址
//
//        if (!ip.equals("0:0:0:0:0:0:0:1")){
//            return;
//        }

        //获取本次请求的uri
        String requestURI = request.getRequestURI();
        //定义不需要处理的请求路径
        String[] uris = new String[]{"/backend/**", "/front/**", "/employee/login","/user/sendMsg","/user/login","/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"};
        //判断本次请求是否需要处理
        boolean flag = check(uris, requestURI);
        //如果不需要处理,直接放行
        if (flag) {
            filterChain.doFilter(request, response);
            return;
        }

        //判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);//将用户id存入当前线程
        if (empId != null) {
            //用户已经登录
            filterChain.doFilter(request, response);
            return;
        }

        //判断移动端用户是否登录
        Long userId = (Long) request.getSession().getAttribute("user");
        BaseContext.setCurrentId(userId);//将用户id存入当前线程
        if (userId != null) {
            //用户已经登录
            filterChain.doFilter(request, response);
            return;
        }
        //用户未登录
        log.info("用户未登录");
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);
    }

    public boolean check(String[] uris, String requestURI) {
        for (String uri : uris) {
            boolean match = new AntPathMatcher().match(uri, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
